package com.example.demo02.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

@Component
public class ValidCodeFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //下面代码表示只过滤/login
        if ("POST".equalsIgnoreCase(request.getMethod()) && "/login".equals(request.getServletPath())) {
            //从前端获取用户填写的验证码
            String requestCode = request.getParameter("code");
            System.out.println("requestCode:" + requestCode);
            String validCode =(String) request.getSession().getAttribute("ValidCode");
            System.out.println("ValidCode:" + validCode);
            //验证码不相同则抛出异常
            if (!validCode.equalsIgnoreCase(requestCode)) {
                //存储错误信息，前端展示
                request.getSession().setAttribute("msg","验证码错误");
                //可以手动抛出异常
                //throw  new AuthenticationServiceException("验证码错误");
                // 重定向到登录页面
                response.sendRedirect("/toLogin");
                return; // 立即返回，不再调用chain.doFilter
            }
        }
        //验证码相同放行 或者不是/login的POST请求，则继续过滤器
        chain.doFilter(request,response);
    }
}
